<?php
/**
 * Created by PhpStorm.
 * User: lengbin
 * Date: 2018-11-27
 * Time: 12:05
 */

namespace common\helpers;

use lengbin\helper\directory\DirHelper;
use lengbin\helper\upload\BaseUploadFile;

class AlbumUpload extends BaseUploadFile
{

    public function __construct($fileKey, $config = null)
    {
        parent::__construct($fileKey, $config);
    }

    /**
     * 定义具体上传文件的实现
     *
     * @param $uniName
     *
     * @return mixed
     */
    protected function invoke($uniName)
    {
        $upload = $this->uploadDir;
        $dir = substr($upload, 0, strrpos($upload, DIRECTORY_SEPARATOR));
        if (!@move_uploaded_file($this->tmpName, $dir . DIRECTORY_SEPARATOR . $uniName)) {
            $this->setError(-4);
            return false;
        }
        if (!$this->dirExistFile($this->uploadDir)) {
            DirHelper::emptyDir($this->uploadDir, [], [], true);
        }
        $this->uploadDir = $dir;
    }

    /**
     * 目录下是否有文件
     * @param $path
     *
     * @return bool
     */
    protected function dirExistFile($path)
    {
        if (!is_dir($path)) {
            return false;
        }
        $files = scandir($path);
        // 删除  "." 和 ".."
        unset($files[0]);
        unset($files[1]);
        // 判断是否为空
        if (!empty($files[2])) {
            return true;
        }
        return false;
    }
}
